package br.it.teste.modelo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.it.teste.banco.BancoHelper;

public class Arma {
	private int id;
	private String nome;
	private String descricao;
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public String getNome() {
		return nome;
	}
	
	public void setNome(String nome) {
		this.nome = nome;
	}
	
	public String getDescricao() {
		return descricao;
	}
	
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}
	
	public String toString(){
		return id + "/" +nome;
	}
	
	public static List<Arma> listarTodas() {
		List<Arma> lista = new ArrayList<Arma>();
		
		try {

			Connection conexao = BancoHelper.getConexao();
			
			String sql = "SELECT Codigo, Nome, Descricao FROM Arma";
			PreparedStatement stmt = conexao.prepareStatement(sql);

			ResultSet rs = stmt.executeQuery();

			while(rs.next()){
				Arma arma = new Arma();
				arma.setId( rs.getInt("Codigo") );
				arma.setNome( rs.getString("Nome") );
				arma.setDescricao( rs.getString("Descricao") );
				
				lista.add(arma);
			}
			
			conexao.close();

		
		} catch (SQLException e) {
			System.out.println("Erro de SQL!");
			e.printStackTrace();
		}
		
		return lista;
	}

	public boolean inserir() {
		boolean salvo = true;
		
		try {

			Connection conexao = BancoHelper.getConexao();
			
			String sql = "INSERT INTO ARMA VALUES (NULL, ?, ?, NOW(), 1); ";
			PreparedStatement stmt = conexao.prepareStatement(sql);
			stmt.setString(1, this.nome);
			stmt.setString(2, this.descricao);

			stmt.execute();

			conexao.close();

		} catch (SQLException e) {
			System.out.println("Erro de SQL!");
			salvo = false;
		}
		
		return salvo;
	}

	public static Arma buscarPorCodigo(int codigoArma) {
		Arma arma = null;
		
		try {

			Connection conexao = BancoHelper.getConexao();
			
			String sql = "SELECT Codigo, Nome, Descricao FROM Arma WHERE Codigo = ?";
			PreparedStatement stmt = conexao.prepareStatement(sql);
			stmt.setInt(1, codigoArma);

			ResultSet rs = stmt.executeQuery();

			if(rs.next()){
				arma = new Arma();
				arma.setId( rs.getInt("Codigo") );
				arma.setNome( rs.getString("Nome") );
				arma.setDescricao( rs.getString("Descricao") );
			}
			
			conexao.close();

		
		} catch (SQLException e) {
			System.out.println("Erro de SQL!");
			e.printStackTrace();
		}
		
		
		return arma;
	}
	
}
